package com.kgc.sbt.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kgc.sbt.api.*;
import com.kgc.sbt.config.annotation.RequestPermission;
import com.kgc.sbt.constant.ActiveMqConstant;
import com.kgc.sbt.domain.*;
import com.kgc.sbt.util.HttpUtils;
import com.kgc.sbt.util.RedisUtils;
import com.kgc.sbt.util.RequestResult;
import com.kgc.sbt.util.ResultBuildUtil;
import io.swagger.annotations.*;
import jdk.nashorn.internal.parser.Token;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.session.SessionProperties;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author Shan
 * @date 2021/6/22
 * @return
 * @description 订单业务入口
 */
@RestController
@Slf4j
@Api(tags = "订单业务操作入口，版本号：1.0.0")
@RequestPermission
public class OrderController {


    @Reference
    private CouponApi couponApi;

    @Reference
    private GoodsApi goodsApi;

    @Reference
    private OrderInfoApi orderInfoApi;

    @Reference
    private OrderItemApi orderItemApi;

    @Reference
    private CouponLogsApi couponLogsApi;

    @Reference
    private OrderApi orderApi;

    @Autowired
    private RedisUtils redisUtils;



    /**
     * @param addressId 地址ID
     * @param couponId  优惠券ID
     * @param goodsId   商品ID数组
     * @param goodsNum  商品数量数组
     * @author Shan
     * @date 2021/6/22
     * @description:创建订单接口
     */
    @PostMapping("/createOrder")
    @RequestPermission
    @ApiOperation(value = "生成商品订单操作", notes = "内部接口，抢购和购物车结算调用。必传用户ID、地址ID、商品ID数组、商品数量数组。")
    public RequestResult<String> createOrder(HttpServletRequest request,
                                             @ApiParam(required = true,name = "addressId", value = "地址ID") @RequestParam Integer addressId,
                                             @ApiParam(required = true,name = "couponId", value = "优惠券ID（0-不使用）") @RequestParam Integer couponId,
                                             @ApiParam(required = true, name = "goodsId", value = "商品ID数组") @RequestParam Integer[] goodsId,
                                             @ApiParam(required = true, name = "goodsNum", value = "商品数量数组") @RequestParam Integer[] goodsNum) {

        // 校验权限，是否已经登录
        String token = request.getHeader("token");

        // 校验token是否有效
        Integer userId = (Integer)redisUtils.get(token);
        log.info("------ userId:" + userId);

        //生成随机订单号
        String OrderNo = "T" + DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now()) + UUID.randomUUID().toString().replace("-", "").substring(0, 5);

        return orderApi.createOrder(userId, addressId, couponId, goodsId, goodsNum, OrderNo, null);

    }

    /**
     * @author Shan
     * @date 2021/6/29
     * @return
     * @description 根据订单编号查询订单
     */

    @GetMapping("/queryOrderByOrderNumber")
    @RequestPermission
    @ApiOperation(value = "根据订单编号查询订单操作", notes = "根据订单编号查询订单操作.")
    public RequestResult<OrderInfo> queryOrderByOrderNumber(HttpServletRequest request, @RequestParam @ApiParam(name = "orderNumber",value = "订单编号") String orderNumber) {

        // 校验权限，是否已经登录
        String token = request.getHeader("token");

        // 校验token是否有效
        Integer userId = (Integer) redisUtils.get(token);
        log.info("------ userId:" + userId);

        OrderInfo orderInfo = orderInfoApi.getOrderInfoByOrderNumber(orderNumber);

        return ResultBuildUtil.success(orderInfo);
    }

    /**
     * @return
     * @author Shan
     * @date 2021/6/23
     * @description 查询订单接口
     */
    @GetMapping("/queryOrderByStatusId")
    @RequestPermission
    @ApiOperation(value = "根据订单状态查询订单操作", notes = "默认查询全部订单.")
    public RequestResult<List<OrderInfo>> queryOrder(HttpServletRequest request, @RequestParam(required = false, defaultValue = "0")@ApiParam(name = "statusId",value = "订单状态ID（1-代付款，2-已支付，3-已发货，4-已签收）") Integer statusId) {

        // 校验权限，是否已经登录
        String token = request.getHeader("token");

        // 校验token是否有效
        Integer userId = (Integer)redisUtils.get(token);
        log.info("------ userId:" + userId);

        //用户的全部订单
        List<OrderInfo> orderInfos = orderInfoApi.queryOrderInfoByUserId(userId);
        //用户根据订单状态查询的订单
        List<OrderInfo> orderInfoList = new ArrayList<>();
        //查询全部
        if (statusId.equals(1) || statusId.equals(2) || statusId.equals(3) || statusId.equals(4)) {
            for (OrderInfo orderInfo : orderInfos) {
                //根据订单状态
                if (orderInfo.getStatusId() == statusId) {
                    //获取订单号
                    String orderNumber = orderInfo.getOrderNumber();
                    //查询该订单的订单详情
                    List<OrderItem> orderItemList = orderItemApi.queryOrderItemByOrderNumber(orderNumber);
                    //订单详细
                    orderInfo.setOrderItemList(orderItemList);
                    //添加到orderInfoList
                    orderInfoList.add(orderInfo);
                }
            }
        } else {
            for (OrderInfo orderInfo : orderInfos) {
                //获取订单号
                String orderNumber = orderInfo.getOrderNumber();
                //查询该订单的订单详情
                List<OrderItem> orderItemList = orderItemApi.queryOrderItemByOrderNumber(orderNumber);
                //订单详细
                orderInfo.setOrderItemList(orderItemList);
                //添加到orderInfoList
                orderInfoList.add(orderInfo);
            }
        }
        return ResultBuildUtil.success(orderInfoList);
    }

    /**
     * @return
     * @author Shan
     * @date 2021/6/24
     * @description 删除订单操作（逻辑删除）
     */
    @PutMapping("/deleteOrder")
    @ApiOperation(value = "删除订单操作（逻辑删除）", notes = "必传订单ID,只能删除未付款和已签收的订单")
    public RequestResult<String> deleteOrderInfo(@ApiParam(required = true,name = "orderInfoId",value = "订单ID")@RequestParam Integer orderInfoId) {

        if (orderInfoApi.deleteOrderInfo(orderInfoId)) {
            return ResultBuildUtil.success("删除成功！");
        }

        return ResultBuildUtil.fail("4001", "删除失败！（请检查订单状态！）");
    }

    /**
     * @return
     * @author Shan
     * @date 2021/6/24
     * @description 修改订单操作
     */
    @PutMapping("/modOrder")
    @ApiOperation(value = "修改订单状态操作", notes = "订单状态改变，内部接口，支付时调用")
    public RequestResult<String> modOrderInfo(@ApiParam(required = true,name = "orderNumber",value = "订单号") @RequestParam String orderNumber,@ApiParam(required = true,name = "status",value = "订单状态") @RequestParam Integer status) {

        if (orderInfoApi.modOrderStatus(orderNumber, status)) {
            return ResultBuildUtil.success("修改成功！");
        }

        return ResultBuildUtil.fail("4001", "修改失败！（请检查订单状态！）");
    }


    /**
     * Created on 2021/6/29
     * Author: guoxu
     * @param
     * @return
     * Description: 根据快递单号查询物流信息
     */
    @GetMapping(value = "/detail")
    @ApiOperation(value = "查询物流信息", notes = "根据快递单号查询物流信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderNumber", required = true, value = "订单编码")
    })
    public RequestResult<JSON> detail(@RequestParam String orderNumber) throws Exception {
//        log.error("============"+orderInfoApi.getOrderInfoByOrderNumber(orderNumber));
        OrderInfo orderInfo = orderInfoApi.getOrderInfoByOrderNumber(orderNumber);

        if (orderInfo == null){
            return ResultBuildUtil.fail("4001","不存在此订单");
        }

        String shipNumber  = orderInfo.getTrackNo();
//        String oType = orderInfo();
        String host = "https://kdwlcxf.market.alicloudapi.com";
        String path = "/kdwlcx";
        String method = "GET";
        String appCode = "d3ee3579878447108e047ac7a9ef2121";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE " + appCode);
        Map<String, String> querys = new HashMap<String, String>();
        querys.put("no", shipNumber.trim());
        HttpResponse response = HttpUtils.doGet(host, path, method, headers, querys);
        //获取response的body
        String ss = EntityUtils.toString(response.getEntity());
        JSONObject json = JSONObject.parseObject(ss);
        Integer issign =Integer.valueOf(json.getJSONObject("result").get("issign").toString());
        log.info("issign===="+issign);
        boolean flag=false;
        if (issign==1){
            //已簽收
          flag=  orderInfoApi.modOrderStatus(orderNumber,4);

        }else if(issign==0){
            // 没有签收
            flag=  orderInfoApi.modOrderStatus(orderNumber,3);
        }
        log.error("flag="+flag);
        //返回json格式
        return ResultBuildUtil.success(json);

    }

    /**
     * @author Shan
     * @date 2021/6/30
     * @return
     * @description 商品发货
     */
    @PutMapping("/sendOrder")
    @ApiOperation(value = "商品发货操作", notes = "必传订单编号,快递单号")
    public RequestResult<String> sendOrder(@ApiParam(required = true,name = "orderNumber",value = "订单编号")@RequestParam String orderNumber,
                                           @ApiParam(required = true,name = "trackNo",value = "物流单号")@RequestParam String trackNo){
        if (orderInfoApi.getOrderInfoByOrderNumber(orderNumber).getStatusId()!=2){
            return ResultBuildUtil.fail("4001","用户未付款！");
        }
        if (orderInfoApi.sendOrder(orderNumber,trackNo)){
            return ResultBuildUtil.success("发货成功！");
        }
        return ResultBuildUtil.fail("4001","发货失败！");
    }


}
